package com.sgcc.operate.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.sgcc.common.datascope.annotation.DataScope;
import com.sgcc.operate.domain.OIndiContent;
import com.sgcc.operate.domain.vo.DateSlot;
import com.sgcc.operate.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sgcc.common.log.annotation.Log;
import com.sgcc.common.log.enums.BusinessType;
import com.sgcc.common.security.annotation.PreAuthorize;
import com.sgcc.operate.domain.OIndiForm;
import com.sgcc.operate.service.IOIndiFormService;
import com.sgcc.common.core.web.controller.BaseController;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.core.utils.poi.ExcelUtil;
import com.sgcc.common.core.web.page.TableDataInfo;

/**
 * 运营指标制定Controller
 *
 * @author sgcc
 * @date 2021-03-23
 */
@RestController
@RequestMapping("/indiform")
public class OIndiFormController extends BaseController {
    @Autowired
    private IOIndiFormService oIndiFormService;

    /**
     * 查询运营指标制定列表
     */
    //@PreAuthorize(hasPermi = "operate:indiform:list")
    @GetMapping("/list")
    @DataScope(deptAlias = "o2")
    public TableDataInfo list(OIndiForm oIndiForm) {
        startPage();
        List<OIndiForm> list = oIndiFormService.selectOIndiFormList(oIndiForm);
        return getDataTable(list);
    }

    /**
     * 导出运营指标制定列表
     */
    //@PreAuthorize(hasPermi = "operate:indiform:export")
    @Log(title = "运营指标制定", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @DataScope(deptAlias = "o2")
    public void export(HttpServletResponse response, OIndiForm oIndiForm) throws IOException {
        List<OIndiForm> list = oIndiFormService.selectOIndiFormList(oIndiForm);
        ExcelUtil<OIndiForm> util = new ExcelUtil<OIndiForm>(OIndiForm.class);
        util.exportExcel(response, list, "form");
    }

    /**
     * 获取运营指标制定详细信息
     */
    //@PreAuthorize(hasPermi = "operate:indiform:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(oIndiFormService.selectOIndiFormById(id));
    }

    /**
     * 新增运营指标制定
     */
    //@PreAuthorize(hasPermi = "operate:indiform:add")
    @Log(title = "运营指标制定", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OIndiForm oIndiForm) {
        return toAjax(oIndiFormService.insertOIndiForm(oIndiForm));
    }

    /**
     * 修改运营指标制定
     */
    //@PreAuthorize(hasPermi = "operate:indiform:edit")
    @Log(title = "运营指标制定", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OIndiForm oIndiForm) {
        return toAjax(oIndiFormService.updateOIndiForm(oIndiForm));
    }

    /**
     * 删除运营指标制定
     */
    //@PreAuthorize(hasPermi = "operate:indiform:remove")
    @Log(title = "运营指标制定", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(oIndiFormService.deleteOIndiFormByIds(ids));
    }


    /**
     * 启用或者禁用，运营指标制定
     */
    @PostMapping(value = "beginOrEnd/{indistatus}/{ids}")
    public AjaxResult deleteAll(@PathVariable String indistatus, @PathVariable String[] ids) {
        for (String id : ids) {
            OIndiForm oIndiForm = oIndiFormService.selectOIndiFormById(id);
            if ("02".equals(oIndiForm.getIndistatus()) && "02".equals(indistatus)) {
                return AjaxResult.error("该运营指标已开启");
            }
            if ("03".equals(oIndiForm.getIndistatus()) && "03".equals(indistatus)) {
                return AjaxResult.error("该运营指标已作废");
            }
            if ("02".equals(oIndiForm.getIndistatus()) && "03".equals(indistatus)) {
                //查看改运营指标是否被运营方案绑定
                List<OIndiContent> list = oIndiFormService.getOIndiContent(id);
                if (list.size() > 0) {
                    return AjaxResult.error("运营指标已被运营方案绑定不能作废！");
                }
            }
            if ("03".equals(oIndiForm.getIndistatus()) && "02".equals(indistatus)) {
                return AjaxResult.error("运营指标已作废不能启用！");
            }

        }

        for (String id : ids) {
            OIndiForm oIndiForm = oIndiFormService.selectOIndiFormById(id);
            oIndiForm.setIndistatus(indistatus);
            oIndiFormService.updateOIndiForm(oIndiForm);
        }
        return AjaxResult.success("操作成功");
    }


    /**
     * 新增修改指标，时间段返回
     */
    @PostMapping(value = "/timeSlot")
    public AjaxResult timeSlot(@RequestBody OIndiForm oIndiForm) {
        if (oIndiForm.getStarttime() != null && oIndiForm.getEndtime() != null && !"03".equals(oIndiForm.getTimedecomode())) {
            if (oIndiForm.getStarttime().compareTo(oIndiForm.getEndtime()) != 1) {
                //计算相差月数
                int monthDiff = DateUtil.getMonthDiff(oIndiForm.getEndtime(), oIndiForm.getStarttime());

                List<DateSlot> list = new ArrayList<>();
                if ("01".equals(oIndiForm.getTimedecomode())) {
                    //按照季度
                    Calendar c1 = Calendar.getInstance();
                    c1.setTime(oIndiForm.getStarttime());
                    int month = c1.get(Calendar.MONTH) + 1;
                    int quarter = 0;
                    //判断季度
                    if (month >= 1 && month <= 3) {
                        quarter = 1;
                    } else if (month >= 4 && month <= 6) {
                        quarter = 2;
                    } else if (month >= 7 && month <= 9) {
                        quarter = 3;
                    } else {
                        quarter = 4;
                    }

                    String str = String.valueOf(c1.get(Calendar.YEAR));
                    String startMonth = "";
                    String endMonth = "";
                    Date firstDay = null;
                    Date lastDay = null;
                    switch (quarter) {
                        case 1: //第一季度
                            startMonth = str + "-01-01";
                            endMonth = str + "-03-01";
                            break;
                        case 2: //第二季度
                            startMonth = str + "-04-01";
                            endMonth = str + "-06-01";
                            break;
                        case 3: //第三季度
                            startMonth = str + "-07-01";
                            endMonth = str + "-09-01";
                            break;
                        case 4: //第四季度
                            startMonth = str + "-10-01";
                            endMonth = str + "-12-01";
                            break;
                    }

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        firstDay = sdf.parse(startMonth);
                        lastDay = sdf.parse(endMonth);
                        //计算结束日期跟季度最后一月，相差的月数
                        int monthDiff1 = DateUtil.getMonthDiff(oIndiForm.getEndtime(), lastDay);
                        BigDecimal divide = new BigDecimal(monthDiff1).divide(new BigDecimal(3), 0, BigDecimal.ROUND_UP);
                        for (int i = 0; i <= divide.intValue(); i++) {
                            DateSlot dateSlot = new DateSlot();
                            dateSlot.setStarttime(firstDay);
                            dateSlot.setEndtime(lastDay);
                            list.add(dateSlot);
                            firstDay = DateUtil.addMonths(firstDay, 3);
                            lastDay = DateUtil.addMonths(lastDay, 3);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if ("02".equals(oIndiForm.getTimedecomode())) {
                    Date tempDate = oIndiForm.getStarttime();
                    //按月
                    for (int i = 0; i < monthDiff + 1; i++) {
                        if (i != 0) {
                            tempDate = DateUtil.addMonths(tempDate, 1);
                        }
                        DateSlot dateSlot = new DateSlot();
                        dateSlot.setStarttime(tempDate);
                        dateSlot.setEndtime(tempDate);
                        list.add(dateSlot);
                    }
                }
                return AjaxResult.success(list);
            } else {
                return AjaxResult.error("开始时间不能大于结束时间");
            }
        }
        return AjaxResult.error("请求参数不完整");
    }


    /**
     * 判断指标定义是否被指标制定引用
     */
    @DataScope(deptAlias = "o2")
    @PostMapping(value = "checkOindidefi")
    public AjaxResult checkOindidefi(OIndiForm oIndiForm) {
        //判断指标是否被指标定义 引用
        oIndiForm.setIndistatus("02");
        List<OIndiForm> list = oIndiFormService.selectOIndiFormList(oIndiForm);
        if (list.size() > 0) {
            return AjaxResult.error("指标名称“" + list.get(0).getIndiname() + "”已被制定且启用");
        } else {
            return AjaxResult.success();
        }
    }


}
